<script setup>
import {
  ElCard, ElScrollbar, ElMessage, ElTabs, ElTabPane, ElForm, ElRow, ElCol, ElFormItem,
} from 'element-plus';
import {
  ref, nextTick, onMounted, computed,
} from 'vue';
import { useRouter } from 'vue-router';
import InsertDialog from '@/components/InsertDialog/InsertDialog.vue';
import cyber from '../../../lib/cybercloud';

const shadow = ref('never');

const updateDialog = ref();

const router = useRouter();

const updateDialogShow = ref(false);

const props = defineProps({
  config: {
    type: Object,
    default() {
      return {};
    },
  },
  buttons: {
    type: Array,
    default() {
      return [];
    },
  },
  dialogConfig: {
    type: Object,
    default() {
      return {};
    },
  },
  form: {
    type: Object,
    default() {
      return {};
    },
  },
  enums: {
    type: Object,
    default() {
      return {};
    },
  },
});
const emit = defineEmits(['update:config']);
const config = computed({
  get() {
    return props.config;
  },
  set(d) {
    emit('update:config', d);
  },
});
function getById() {
  return cyber.request({
    method: 'POST',
    url: '/api/app/corm/get',
    data: {
      objectId: config.value.objectId,
      params: {
        id: config.value.id,
      },
    },
  }).then((res) => {
    if (res.success) {
      const resData = res.data;
      if (resData.code) {
        config.value.code = resData.code;
      } else {
        config.value.code = '';
      }
      Object.values(props.form.data).forEach((d) => {
        Object.values(d.groups).forEach((group) => {
          Object.values(group.items).forEach((item) => {
            item.value = resData[item.code];
            if (item.value instanceof Object) {
              const attributes = item.value.displayFields; // displayFields 平台固定关联对象名
              const arr = [];
              Object.values(attributes)
                .forEach((obj) => {
                  arr.push(obj.value);
                });
              item.value = arr.join(',');
            }
            if (item.conversionEnums.need && resData[item.code]
              && props.enums[item.conversionEnums.enumName] !== undefined) {
              Object.values(props.enums[item.conversionEnums.enumName]).forEach((enums) => {
                if (enums.value === resData[item.code]) {
                  item.value = enums.label;
                }
              });
            }
          });
        });
      });
    } else {
      ElMessage.error('获取详情失败');
    }
  }).catch(() => {
    ElMessage.error('获取详情失败');
  });
}
function reload() {
  getById();
}

function findDataForUpdate() {
  return cyber.request({
    method: 'POST',
    url: '/api/app/corm/get',
    data: {
      objectId: props.config.objectId,
      params: {
        id: props.config.id,
      },
    },
  }).then((res) => {
    if (res.success) {
      const resData = res.data;
      props.dialogConfig.formData.details?.forEach((d) => {
        d.items?.forEach((item) => {
          if (resData[item.code] instanceof Object) {
            item.value = resData[item.code].value;
            item.selectRemote.optionsData.data = [];
            const option = {
              label: '',
              value: item.value,
              code: '',
            };
            resData[item.code].displayFields.forEach((displayField) => {
              if (item.selectRemote.optionsData.attribute.label === displayField.code) {
                option.label = displayField.value;
              }
              if (item.selectRemote.optionsData.attribute.code === displayField.code) {
                option.code = displayField.value;
              }
            });
            if (item.value !== null && item.value !== '') {
              item.selectRemote.optionsData.data.push(option);
            } else {
              item.selectRemote.optionsData.data = [];
            }
          } else {
            item.value = resData[item.code];
          }
        });
      });
      updateDialogShow.value = true;
      nextTick(() => {
        updateDialog.value.openDialog();
      });
    } else {
      ElMessage.error('获取失败');
    }
  })
    .catch(() => {
      ElMessage.error('获取失败');
    });
}
function buttonClick(action, index) {
  // 此处方法可自定义修改
  if (action === 'back') {
    router.push({ path: props.buttons[index].backPath });
  } else if (action === 'update') {
    findDataForUpdate();
  }
}
function handleClick() {
  // tabs 触发
}
function closeDialog() {
  updateDialogShow.value = false;
}
function submitSuccess() {
  updateDialogShow.value = false;
  getById();
}
defineExpose({
  reload,
});
onMounted(() => {
  if (props.config.initData) {
    reload();
  }
});
</script>
<template>
  <div class="detail">
    <div>
      <el-card :shadow="shadow" class="headerCart">
        <div class="header">
          <div>
            <div class="headerLeftTitle">
              {{ config.name }}
            </div>
            <div class="headerLeftCode">
              {{ config.code }}
            </div>
          </div>
          <div class="headerRight">
            <C-Button @click="buttonClick(button.action,index)"
                      v-for="(button,index) in buttons" :key="index"
                      :icon="button.icon"
                      :type="button.type">
              <div v-if="!button.icon" class="headerButtonContent">{{ button.name }}</div>
              <div v-else class="headerButtonContent">
                <component :is="button.name" class="headerButtonIcon"/>
              </div>
            </C-Button>
          </div>
        </div>
      </el-card>
    </div>
    <div class="content">
      <el-scrollbar>
        <el-tabs v-model="config.activeName" class="contentTabs" @tab-click="handleClick">
          <el-tab-pane v-for="(tabPane,index) in form.data" :key="index"
                       :label="tabPane.label" :name="tabPane.name">
            <div class="contentTabPane"
                 v-for="(group,key) in tabPane.groups" :key="key">
              <div class="contentTabPaneTitle">
                <div>{{ group.name }}</div>
                <div style="height: 40px;width: 2px;background: #409eff;margin-left: 20px"></div>
              </div>
              <div class="contentTabPaneItem">
                <el-form :ref="tabPane.config.formRef"
                         :model="form"
                         :rules="tabPane.config.rules"
                         :label-width="120"
                         label-position="right"
                >
                  <el-row :gutter="20">
                    <el-col :span="item.span? 24/item.span : 24 "
                            v-for="(item,idx) in group.items" :key="idx">
                      <el-form-item :label="item.name"
                                    :prop="`data[${index}].groups[${key}].items[${idx}].value`"
                                    :rules="item.rules.rulesName"
                      >{{ item.value }}
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-scrollbar>
    </div>
    <InsertDialog
      v-if="updateDialogShow"
      ref="updateDialog"
      :enums = 'enums'
      :dialogConfig="dialogConfig"
      @closeDialog='closeDialog'
      @submitSuccess='submitSuccess'
    ></InsertDialog>
  </div>
</template>
<style scoped lang="sass">
@import "Detail.sass"
</style>
